<template>
  <div>
    <Header>
      <div class="h-full flex items-center justify-between gap-2">
        <template v-if="id">
          <el-button type="warning" @click="handleUpdate">更新问卷</el-button>
        </template>
        <div v-else>
          <el-button type="danger" @click="handleReset">重置问卷</el-button>
          <el-button type="primary" @click="handleSave">保存问卷</el-button>
        </div>
        <el-button v-if="id" type="success" plain @click="handlePreview">
          预览
        </el-button>
      </div>
    </Header>
    <div class="editor-container">
      <LeftSide />
      <Center />
      <RightSide />
    </div>
  </div>
</template>

<script setup lang="ts">
import Header from "@/components/Common/Header.vue";
import LeftSide from "@/views/Editor/LeftSide/Index.vue";
import RightSide from "@/views/Editor/RightSide/Index.vue";
import Center from "@/views/Editor/Center/Index.vue";
import { useEditorStore } from "@/stores/useEditor";
import type { IUpdateStatus } from "@/types/common";
import { dispatchStatus } from "@/utils/provideFuncs";
import { ElMessage, ElMessageBox } from "element-plus";
import type { ISurveyDB } from "@/types";
import { useRoute, useRouter } from "vue-router";
import { restoreComJsonSchema } from "@/utils/dbUtils";

const router = useRouter();
const route = useRoute();
// - 获取问卷id(编辑问卷时)
const id = computed(() => Number(route.params.id || ""));

const editorStore = useEditorStore();
const { getCurrentComJsonSchema } = storeToRefs(editorStore);

if (id.value && id.value !== 0) {
  // - 如果有问卷id，说明是编辑问卷，需要获取问卷
  editorStore.getSurveyById(id.value).then((res) => {
    if (res) {
      // - 还原组件的jsonSchema
      restoreComJsonSchema(res.coms);
      // - 设置组件列表
      editorStore.setComs(res.coms);
    }
  });
}

// * 重置画布
const handleReset = () => {
  ElMessageBox.confirm("确定重置画布吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      editorStore.resetComs();
      ElMessage.success("重置画布成功");
    })
    .catch(() => ElMessage.info("已取消重置画布"));
};

// * 保存问卷
const handleSave = () => {
  ElMessageBox.prompt("请输入问卷名称", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(({ value }) => {
      const surveyData: ISurveyDB = {
        title: value,
        coms: JSON.parse(JSON.stringify(editorStore.coms)),
        createTime: new Date().getTime(),
        updateTime: new Date().getTime(),
      };
      editorStore
        .saveComs(surveyData)
        .then((id) => {
          router.push(`/editor/${id}/survey-types`);
          ElMessage.success("保存问卷成功");
        })
        .catch(() => {
          ElMessage.error("保存问卷失败");
        });
    })
    .catch(() => ElMessage.info("已取消保存问卷"));
};

// * 更新问卷
const handleUpdate = async () => {
  try {
    await ElMessageBox.confirm("确定更新问卷吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    });
    await editorStore.updateComs({
      id: id.value,
      title: "更新问卷",
      coms: JSON.parse(JSON.stringify(editorStore.coms)),
      updateTime: new Date().getTime(),
    });
    ElMessage.success("已更新问卷");
  } catch (error) {
    ElMessage.info("已取消更新问卷");
  }
};

// * 预览问卷
const handlePreview = () => {
  // router.push(`/preview/${id.value}`);
  ElMessageBox.confirm("预览问卷需要保存，是否保存？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(async () => {
      await editorStore.updateComs({
        id: id.value,
        title: "更新问卷",
        coms: JSON.parse(JSON.stringify(editorStore.coms)),
        updateTime: new Date().getTime(),
      });
      router.push({
        path: `/preview/${id.value}`,
        state: { from: "editor" },
      });
    })
    .catch(() => {
      ElMessage.info("已取消预览问卷");
    });
};

// * 更新状态
const updateStatus: IUpdateStatus = (statusKey, value) => {
  // console.log(statusKey, value);
  if (value !== undefined) {
    dispatchStatus(
      editorStore,
      getCurrentComJsonSchema.value!.status,
      statusKey,
      value,
    );
  }
};

// * 设置图片链接
const setImageUrl = (index: number, link: string) => {
  // updateStatus("options", { index, link });
  updateStatus("options", {
    index,
    link,
  });
};

// - 提供更新状态的方法
provide("updateStatus", updateStatus);

// - 提供获取图片链接的方法
provide("setImageUrl", setImageUrl);

defineOptions({
  meta: {
    title: "问卷编辑",
    __isRouteComponent: true,
    __redirect: "/src/views/Editor/LeftSide/SurveyTypes.vue",
    __props: {
      id: {
        reg: "(\\d+)?",
      },
    },
  },
});
</script>

<style scoped lang="scss">
.editor-container {
  height: calc(100vh - 64px);
  width: 100vw;
  padding: 20px;
  background: url("@/assets/imgs/editor_background.png");
  display: flex;
  justify-content: space-between;
  gap: 24px;
  min-width: 1300px;
}
</style>
